package com.example.rouroudate.ui.gallery

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.example.rouroudate.R
import com.example.rouroudate.databinding.ActivityGalleryBinding
import com.example.rouroudate.ui.gallery.ui.DateSettingDialog
import com.example.rouroudate.ui.gallery.ui.StyleAnimationView
import com.example.rouroudate.ui.gallery.ui.StyleSettingDialog
import com.example.rouroudate.ui.widget.BaseActivity
import com.example.rouroudate.ui.widget.CurrentDateSetDialog
import com.example.rouroudate.ui.widget.DataEventBus
import com.example.rouroudate.util.DisplayUtils
import com.example.rouroudate.util.PermissionUtils
import com.example.rouroudate.util.PrefManager
import com.example.rouroudate.util.ToastUtils
import kotlinx.coroutines.launch

class GalleryActivity : BaseActivity() {

    companion object {
        private const val date = 0
        private const val born = 1
        private const val style = 2
        private const val file = 3
    }

    private lateinit var binding: ActivityGalleryBinding

    private lateinit var container: LinearLayout

    private var views = arrayListOf<View>()

    private val galleryRequestCode = 100

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityGalleryBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initView()
    }

    private fun initView() {
        binding.titleBar.apply {
            titleTv.setTextColor(ContextCompat.getColor(this@GalleryActivity, R.color.pink))
            titleTv.text = getString(R.string.menu_gallery)
            leftView.background = AppCompatResources.getDrawable(this@GalleryActivity, R.drawable.ic_back)
            leftView.setOnClickListener {
                finish()
            }
        }
        container = binding.galleryContent
        initSettingView()
        initEvent()
    }

    private fun initSettingView() {
        views.add(View.inflate(this, R.layout.line_item_layout, null).apply {
            setOnClickListener(::handlerDateSetting)
            initChildView(this, R.drawable.ic_date_setting, R.string.date_set, kotlin.run {
                val dateSettingData = PrefManager.getDateSetting()
                String.format("%s天，%s天", dateSettingData.dateSize, dateSettingData.hurtSize)
            })
        })
        views.add(View.inflate(this, R.layout.line_item_layout, null).apply {
            setOnClickListener(::handlerBornSetting)
            initChildView(this, R.drawable.ic_born_setting, R.string.born_set, PrefManager.getBornSetting().getStr())
        })
        views.add(View.inflate(this, R.layout.line_item_layout, null).apply {
            setOnClickListener(::handlerStyleSetting)
            val (bg, value) = when(PrefManager.getStyleType()) {
                StyleAnimationView.HeartType -> arrayOf(R.drawable.ic_style_setting_heart, getString(R.string.style_heart))
                StyleAnimationView.FiveASType -> arrayOf(R.drawable.ic_style_setting_polygon, getString(R.string.style_polygon))
                else -> arrayOf(R.drawable.ic_style_setting_circle, getString(R.string.style_circle))
            }
            initChildView(this, bg as Int, R.string.style_set, value as String)
        })
        views.add(View.inflate(this, R.layout.line_item_layout, null).apply {
            setOnClickListener(::handlerSaveFile)
            initChildView(this, R.drawable.ic_file_setting, R.string.save_file, "")
        })
//        views.add(View.inflate(this, R.layout.line_item_layout, null).apply {
//            setOnClickListener(::handlerImportFile)
//            initChildView(this, R.drawable.ic_file_setting, R.string.import_file, "")
//        })
        val lp = ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, DisplayUtils.dp2px(50f)).apply {
            val margin = DisplayUtils.dp2px(10f)
            topMargin = margin
            bottomMargin = margin
        }
        views.forEach { container.addView(it, lp) }
    }

    private fun initEvent() {
        lifecycleScope.launch {
            DataEventBus.dateSettingData.collect {
                views[date].findViewById<TextView>(R.id.value_tv).text = String.format("%s天，%s天", it.dateSize, it.hurtSize)
            }
        }
        lifecycleScope.launch {
            DataEventBus.styleSettingType.collect {
                val (bg, value) = when(PrefManager.getStyleType()) {
                    StyleAnimationView.HeartType -> arrayOf(R.drawable.ic_style_setting_heart, getString(R.string.style_heart))
                    StyleAnimationView.FiveASType -> arrayOf(R.drawable.ic_style_setting_polygon, getString(R.string.style_polygon))
                    else -> arrayOf(R.drawable.ic_style_setting_circle, getString(R.string.style_circle))
                }
                initChildView(views[style], bg as Int, R.string.style_set, value as String)
            }
        }
    }

    private fun handlerBornSetting(view: View) {
        val dialog = this@GalleryActivity.let { it1 ->
            CurrentDateSetDialog(it1).apply {
                setTitle(getString(R.string.born_set))
                selectedDay = PrefManager.getBornSetting()
                setCallBack {
                    ToastUtils.show(if (PrefManager.setBornSetting(it)) {
                        views[born].findViewById<TextView>(R.id.value_tv).text = it.getStr()
                        getString(R.string.edit_success)
                    } else {
                        getString(R.string.edit_fail)
                    })
                }
            }
        }
        dialog.show()
    }

    private fun handlerImportFile(view: View) {
        val permissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
        val needPermissions = PermissionUtils.checkPermission(this, permissions)
        if (needPermissions.isEmpty()) {
            PrefManager.importFile()
        } else {
            PermissionUtils.requestPermission(this, needPermissions, galleryRequestCode)
        }
    }

    private fun handlerSaveFile(view: View) {
        val permissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
        val needPermissions = PermissionUtils.checkPermission(this, permissions)
        if (needPermissions.isEmpty()) {
            PrefManager.saveFile()
        } else {
            PermissionUtils.requestPermission(this, needPermissions, galleryRequestCode)
        }
    }

    private fun handlerStyleSetting(view: View) {
        val dialog = this@GalleryActivity.let { it1 ->
            StyleSettingDialog(it1).apply {
                setTitle(getString(R.string.style_set))
            }
        }
        dialog.show()
    }

    private fun handlerDateSetting(view: View) {
        val dialog = this@GalleryActivity.let { it1 ->
            DateSettingDialog(it1).apply {
                setTitle(getString(R.string.date_set))
            }
        }
        dialog.show()
    }

    private fun initChildView(view: View, bg: Int, keyText: Int, valueText: String) {
        view.findViewById<ImageView>(R.id.icon_iv).apply {
            background = ContextCompat.getDrawable(this@GalleryActivity, bg)
        }
        view.findViewById<TextView>(R.id.key_tv).apply {
            text = getString(keyText)
        }
        view.findViewById<TextView>(R.id.value_tv).apply {
            text = valueText
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == galleryRequestCode) {
            for (i in permissions.indices) {
                if (permissions[i] == Manifest.permission.WRITE_EXTERNAL_STORAGE && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    ToastUtils.show("申请成功")
                }
            }
        }
    }
}